

package com.kimo.shop.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kimo.shop.bean.model.Category;
import com.kimo.shop.bean.model.Product;
import com.kimo.shop.bean.model.RetailProd;
import com.kimo.shop.common.annotation.SysLog;
import com.kimo.shop.common.config.Constant;
import com.kimo.shop.common.exception.KimoShopBindException;
import com.kimo.shop.common.i18n.I18nMessage;
import com.kimo.shop.common.i18n.LanguageEnum;
import com.kimo.shop.security.admin.util.SecurityUtils;
import com.kimo.shop.service.CategoryService;
import com.kimo.shop.service.ProductService;
import com.kimo.shop.service.RetailProdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 分类管理
 * @author kimo-taozhouchuan
 *
 */
@RestController
@RequestMapping("/prod/category")
public class CategoryController {

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private ProductService productService;

	@Autowired
	private RetailProdService retailProdService;
	/**
	 * 获取菜单页面的表
	 * @return
	 */
	@GetMapping("/list")
	@PreAuthorize("@pms.hasPermission('prod:category:page')")
	public ResponseEntity<List<Category>> table(){
//		List<Category> categoryMenuList = categoryService.list(new LambdaQueryWrapper<Category>().eq(Category::getShopId,SecurityUtils.getSysUser().getShopId()));
//		// 设置名称
//		Integer dbLang = I18nMessage.getDbLang();
//		for (Category category : categoryMenuList) {
//			if(Objects.equals(dbLang,1) && Objects.nonNull(category.getCategoryNameEn())){
//				category.setCategoryName(category.getCategoryNameEn());
//			}
//		}
		Category category = new Category();
		category.setShopId(SecurityUtils.getSysUser().getShopId());
		category.setLang(I18nMessage.getLang());
		List<Category> categoryMenuList =  categoryService.categoryList(category);
		return ResponseEntity.ok(categoryMenuList);
	}

	/**
	 * 获取分类信息
	 */
	@GetMapping("/info/{categoryId}")
	public ResponseEntity<Category> info(@PathVariable("categoryId") Long categoryId){
//		Category category = categoryService.getById(categoryId)
		Category category = categoryService.getCategoryByCategoryId(categoryId);
		return ResponseEntity.ok(category);
	}



	/**
	 * 保存分类
	 */
	@SysLog("保存分类")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('prod:category:save')")
	public ResponseEntity<Void> save(@RequestBody Category category){
		category.setShopId(SecurityUtils.getSysUser().getShopId());
		category.setRecTime(new Date());
//        int count = categoryService.count(new LambdaQueryWrapper<Category>().eq(Category::getCategoryName,category.getCategoryName())
//				.eq(Category::getShopId,category.getShopId()))
		Integer count = categoryService.getCategoryName(category);
        if(count > 0){
            // 类目名称已存在
            throw new KimoShopBindException(I18nMessage.getMessage("kimo.category.name.exist"));
        }
		category.setSuperiorId(-1L);
		// 获取上级的上级
		if(category.getGrade() == 2) {
			Long superiorId = categoryService.getParentCategoryByParentId(category.getParentId());
			if (superiorId == null){
				category.setSuperiorId(-1L);
			}else {
				category.setSuperiorId(superiorId);
			}
		}
		category.setGrade(getGradeByParentId(category.getParentId()));
		categoryService.saveCategroy(category);
		// 清除缓存
		removeCategoryCacheByParentId(category);
		return ResponseEntity.ok().build();
	}

	/**
	 * 更新分类
	 */
	@SysLog("更新分类")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('prod:category:update')")
	public ResponseEntity<String> update(@RequestBody Category category){
		category.setShopId(SecurityUtils.getSysUser().getShopId());
		Category categoryDB = categoryService.getById(category.getCategoryId());
		if (Objects.equals(categoryDB.getParentId(), Constant.CATEGORY_ID) && !Objects.equals(category.getParentId(), Constant.CATEGORY_ID)){
			// 一级分类不能改为二级分类
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("kimo.category.one.check"));
		}else if(Objects.equals(category.getParentId(), Constant.CATEGORY_ID) && !Objects.equals(categoryDB.getParentId(), Constant.CATEGORY_ID)){
			// 二级分类不能改为一级分类
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("kimo.category.two.check"));

		}
		if (Objects.equals(category.getParentId(),category.getCategoryId())) {
			// 分类的上级不能是自己本身
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("kimo.category.superior.check"));
		}
//		int count = categoryService.count(new LambdaQueryWrapper<Category>().eq(Category::getCategoryName,category.getCategoryName())
//				.eq(Category::getShopId,category.getShopId()).ne(Category::getCategoryId,category.getCategoryId()))
		Integer count = categoryService.getCategoryName(category);
		if(count > 0){
			// 类目名称已存在
			throw new KimoShopBindException(I18nMessage.getMessage("kimo.category.name.exist"));
		}
		// 如果从下线改成正常，则需要判断上级的状态
		if (Objects.equals(categoryDB.getStatus(),0) && Objects.equals(category.getStatus(),1) && !Objects.equals(category.getParentId(),0L)){
			Category parentCategory = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryId, category.getParentId()));
			if(Objects.isNull(parentCategory) || Objects.equals(parentCategory.getStatus(),0)){
				// 修改失败，上级分类不存在或者不为正常状态
				throw new KimoShopBindException("kimo.category.status.check");
			}
		}
		category.setOldCategoryName(categoryDB.getCategoryName());
		category.setGrade(getGradeByParentId(category.getParentId()));
		category.setSuperiorId(-1L);
		// 获取上级的上级
		if(category.getGrade() == 2) {
			Long superiorId = categoryService.getParentCategoryByParentId(category.getParentId());
			if (superiorId == null){
				category.setSuperiorId(-1L);
			}else {
				category.setSuperiorId(superiorId);
			}
		}
		categoryService.updateCategroy(category);
		// 清除缓存
		removeCategoryCacheByParentId(category);
		return ResponseEntity.ok().build();
	}

	private void removeCategoryCacheByParentId(Category category) {
		categoryService.removeCacheByParentIdAndLang(category.getParentId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
		categoryService.removeCacheByParentIdAndLang(category.getParentId(), LanguageEnum.LANGUAGE_EN.getLang());
		categoryService.removeCacheByParentIdAndLang(category.getSuperiorId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
		categoryService.removeCacheByParentIdAndLang(category.getSuperiorId(), LanguageEnum.LANGUAGE_EN.getLang());
		// 如果是2/3级分类，第一分类也需要清空缓存数据
		if(category.getGrade() == 1 || category.getGrade() == Constant.MAX_CATEGORY_GRADE) {
			categoryService.removeCacheByParentIdAndLang(Constant.CATEGORY_ID, LanguageEnum.LANGUAGE_ZH_CN.getLang());
			categoryService.removeCacheByParentIdAndLang(Constant.CATEGORY_ID, LanguageEnum.LANGUAGE_EN.getLang());
		}
	}

	/**
	 * 删除分类
	 */
	@SysLog("删除分类")
	@DeleteMapping("/{categoryId}")
	@PreAuthorize("@pms.hasPermission('prod:category:delete')")
	public ResponseEntity<String> delete(@PathVariable("categoryId") Long categoryId){
		if (categoryService.count(new LambdaQueryWrapper<Category>().eq(Category::getParentId,categoryId)) >0) {
			// 请删除子分类，再删除该分类
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("kimo.category.delete.child"));
		}
		int categoryProdCount = productService.count(new LambdaQueryWrapper<Product>().eq(Product::getCategoryId, categoryId).ne(Product::getStatus, -1));
		if (categoryProdCount>0){
			// 该分类下还有商品，请先删除该分类下的商品
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("kimo.category.delete.check"));
		}
		Category category = categoryService.getById(categoryId);
		category.setSuperiorId(-1L);
		// 获取上级的上级
		if(category.getGrade() == 2) {
			Long superiorId = categoryService.getParentCategoryByParentId(category.getParentId());
			if (superiorId == null){
				category.setSuperiorId(-1L);
			}else {
				category.setSuperiorId(superiorId);
			}
		}
		categoryService.deleteCategroy(category);
		// 清除缓存
		removeCategoryCacheByParentId(category);
		return ResponseEntity.ok().build();
	}

	/**
	 * 所有的
	 */
	@GetMapping("/listCategory")
	public ResponseEntity<List<Category>> listCategory(@RequestParam(value = "maxGrade",required = false,defaultValue = "2") Integer maxGrade,
													   @RequestParam(value = "status",required = false) Integer status){
//		List<Category> categories = categoryService.list(new LambdaQueryWrapper<Category>()
//				.le(Category::getGrade, maxGrade)
//				.eq(Objects.nonNull(status), Category::getStatus, status)
//				.eq(Category::getShopId, SecurityUtils.getSysUser().getShopId())
//				.orderByAsc(Category::getSeq));
//		for (Category category : categories) {
//			category.setCategoryName(Objects.equals(I18nMessage.getDbLang(),1)?category.getCategoryNameEn():category.getCategoryName());
//		}
		List<Category> list =  categoryService.listByLang(I18nMessage.getLang(),maxGrade,null, status, Constant.PLATFORM_SHOP_ID);
		return ResponseEntity.ok(list);
	}

	/**
	 * 获取上架分类和当前选中分类的父类
	 * maxGrade==2 返回包括本身的分类，否则不包括
	 */
	@GetMapping("/upAndCurrCategoryList/{categoryId}")
	public ResponseEntity<List<Category>> getUpAndCurrCategoryList(
			@RequestParam(value = "maxGrade", required = false, defaultValue = "2") Integer maxGrade,
			@PathVariable("categoryId") Long categoryId){

		Category category = new Category();
		category.setLang(I18nMessage.getDbLang());
		category.setStatus(1);
		category.setShopId(Constant.PLATFORM_SHOP_ID);
		category.setGrade(maxGrade);
		//获取上架的分类
		List<Category> upList = categoryService.categoryList(category);

		//如果是新增的，直接返回上架的分类即可
		if (categoryId==0){
			return ResponseEntity.ok(upList);
		}

		//当前选中的父分类
		List<Category> currCateParentsList = new ArrayList<>();
//		Category currCategory = categoryService.getById(categoryId)
		Category currCategory = categoryService.getCategoryByCategoryId(categoryId);
		if (currCategory != null) {
			//返回本身的分类，且是下线状态
			if(maxGrade==2 && currCategory.getStatus()==0){
				currCateParentsList.add(currCategory);
			}
			while (currCategory.getParentId() != 0) {
//				currCategory = categoryService.getById(currCategory.getParentId())
				currCategory = categoryService.getCategoryByCategoryId(currCategory.getParentId());
				if (currCategory.getStatus() == 0) {
					//下线状态才加入，否则重复
					currCateParentsList.add(currCategory);
				}
			}

			//将当前分类的父分类加到上架的分类
			if (currCateParentsList.size() > 0){
				upList.addAll(currCateParentsList);
			}
		}

		return ResponseEntity.ok(upList);
	}

	/**
	 *通过商品id获取上架分类和当前选中分类的父类
	 * @param retailProdId
	 */
	@GetMapping("/getCateListByRetProdId/{retailProdId}")
	public ResponseEntity<List<Category>> getCategoryListByProdId(@PathVariable("retailProdId") Long retailProdId){
		RetailProd retailProd = retailProdService.getInfo(retailProdId);
		if (retailProd!=null && retailProd.getCategoryId()!=null){
			return getUpAndCurrCategoryList(2, retailProd.getCategoryId());
		}
		return getUpAndCurrCategoryList(2, 0L);
	}

	private int getGradeByParentId(Long parentId) {
		// 如果上级为id为0，则设置分类等级为0
		if (Objects.equals(parentId,0L)) {
			return 0;
		}
		Category parentCategory = categoryService.getById(parentId);
		return parentCategory.getGrade() + 1;
	}

}
